from odoo import fields, models, _
from odoo.exceptions import ValidationError


class WorkorderReworkOrRemark(models.TransientModel):
    _name = 'workorder.redo.wizard'
    _description = 'Manufacturing Order Rework/Remake'

    production_id = fields.Many2one('mrp.production', 'Source Manufacturing Order', required=True, check_company=True,
                                    readonly=True)
    qty_production = fields.Float('Quantity', readonly=True, related='production_id.product_qty')
    qty_done = fields.Float(string='Processed Quantity', readonly=True, digits='Product Unit of Measure')
    qty_reject = fields.Float(string='Scrap', readonly=True, related='production_id.qty_reject')
    mo_type = fields.Selection([
        ('N', 'Normal'), ('R', 'Rework'), ('M', 'Remake')
    ], string='Processing Type', default='N', required=True, readonly=True)
    todo = fields.Float(string='Pending Quantity', digits='Product Unit of Measure')

    def button_done(self):
        todo = self.todo or 0
        if todo <= 0:
            raise ValidationError(_('The processed quantity cannot be less than or equal to 0.'))

        p = self.production_id
        vals = {
            'mo_type': self.mo_type,
            'product_id': p.product_id.id,
            'bom_id': p.bom_id.id,
            'picking_type_id': p.picking_type_id.id,
            'product_qty': self.todo,
            'product_uom_id': p.product_id.uom_id.id,
            'user_id': self.env.user.id,
            'origin': p.name,
            'srce_rm_mo': p.name
        }
        productions = self.env['mrp.production'].with_user(self.env.user).sudo().with_company(self.env.company.id).create(vals)
        msgs = {}
        if self.mo_type in ['M']:
            productions.action_confirm()
        else:
            msgs = {
                'type': 'ir.actions.client',
                'tag': 'display_notification',
                'params': {
                    'title': _("Rework"),
                    'type': 'warning',
                    'message': _(
                        "Processing successful, Rework Order: %s, please adjust the rework process, materials, etc., and confirm the order",
                        productions.name),
                    'sticky': True,
                    'next': {
                        'type': 'ir.actions.act_window_close'
                    },
                }
            }
        return msgs